import mongoose from 'mongoose';

const LoggerSchema = new mongoose.Schema(
  {
    user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
    name: String, // 日志名称
    extra: Object, // 其他参数
    create_time: Date // 创建时间
  },
  { versionKey: false }
);
LoggerSchema.index({ user: 1 }, { sparse: true });
LoggerSchema.index({ name: 1 }, { sparse: true });

/**
 * 新增日志
 * @param {String} parmas.userid 用户ID
 * @param {String} parmas.memberName 会员名称
 */
LoggerSchema.statics.addLog = async function (parmas) {
  const { userid, name, extra = null } = parmas;
  if (!name) throw new Error('setMember参数错误');
  await this.create({
    user: mongoose.Types.ObjectId(userid),
    name,
    extra,
    create_time: new Date()
  });
  return true;
};

const Logger = mongoose.model('Logger', LoggerSchema);

export { Logger };
